import javax.swing.tree.TreeNode;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:何人亮
 * Date:2024-08-26
 * 18:59
 */
public class Test {
    public static void main(String[] args) {
        Solution s=new Solution();
        Solution.TreeNode root=s.new TreeNode(1);
        Solution.TreeNode root1=s.new TreeNode(2);
        Solution.TreeNode root2=s.new TreeNode(3);
        Solution.TreeNode root3=s.new TreeNode(4);
        root.left=root1;
        root1.left=root2;
        root1.right=root3;
        root.right=null;
        s.tree2str(root);
    }
}

class Solution {
    public class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }

    public  String tree2str(TreeNode root) {
        StringBuilder stringBuilder=new StringBuilder();
         tree2strChild(root,stringBuilder);
         return stringBuilder.toString();
    }

    private  String tree2strChild(TreeNode root,StringBuilder stringBuilder) {
        if(root==null){
            return null;
        }
        stringBuilder.append(root.val);
        if(root.left!=null){
            stringBuilder.append("(");
            tree2strChild(root.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if(root.right==null) {
                return null;
            }else {
                stringBuilder.append("()");
            }
        }
        if(root.right!=null){
            stringBuilder.append("(");
            tree2strChild(root.right,stringBuilder);
            stringBuilder.append(")");
        }else{
            return null;
        }
        return stringBuilder.toString();
    }


}